package com.isunland.managesystem.ui;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.SysDistrict;
import com.isunland.managesystem.entity.SysDistrictListOriginal;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import java.util.ArrayList;
import org.json.JSONException;

/**
 * 对象功能: 地址选择弹窗
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: wangyanan
 * 创建时间: 2017/3/16 15:32
 */
public class AddressSelectDialogFragment extends DialogFragment
    implements AdapterView.OnItemClickListener {

  public static final String EXTRA_CODE =
      AddressSelectDialogFragment.class.getSimpleName() + ".EXTRA_CODE";
  public static final String EXTRA_NAME =
      AddressSelectDialogFragment.class.getSimpleName() + ".EXTRA_NAME";
  public static final String EXTRA_CODE_DISTRICT =
      AddressSelectDialogFragment.class.getSimpleName() + ".EXTRA_CODE_DISTRICT";
  private static final String EXTRA_MEMBER_CODE =
      AddressSelectDialogFragment.class.getSimpleName() + ".EXTRA_MEMBER_CODE";
  @BindView(R.id.pb_loading) ProgressBar pbLoading;
  @BindView(R.id.tv_address0) TextView tvAddress0;
  @BindView(R.id.tv_address1) TextView tvAddress1;
  @BindView(R.id.tv_address2) TextView tvAddress2;
  @BindView(R.id.tv_address3) TextView tvAddress3;
  @BindView(R.id.tv_address4) TextView tvAddress4;
  @BindView(R.id.lv_address) ListView lvAddress;
  private AlertDialog mDialog;
  private BaseVolleyActivity mActivity;
  //private String mCode;//地域编码
  private ArrayList<SysDistrict> mList;
  //private ListView mListView;
  private ArrayAdapter<SysDistrict> mAdapter;
  private SysDistrict mItem;
  private int mLevel;
  private String mCode;//传过来的code
  /** 可选级别,如2,只能选到市 */
  private String mMemberCode;
  /** 是否在执行接口,防止重复点击 */
  private boolean mIsLoading;

  public static DialogFragment newInstance(String code) {
    AddressSelectDialogFragment fragment = new AddressSelectDialogFragment();
    Bundle bundle = new Bundle();
    bundle.putString(EXTRA_CODE, code);
    fragment.setArguments(bundle);
    return fragment;
  }

  public static DialogFragment newInstance(String code, String memberCode) {
    AddressSelectDialogFragment fragment = new AddressSelectDialogFragment();
    Bundle bundle = new Bundle();
    bundle.putString(EXTRA_CODE, code);
    bundle.putString(EXTRA_MEMBER_CODE, memberCode);
    fragment.setArguments(bundle);
    return fragment;
  }

  @Override public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mActivity = (BaseVolleyActivity) getActivity();
    mCode = getArguments().getString(EXTRA_CODE);
    mMemberCode = getArguments().getString(EXTRA_MEMBER_CODE);
    mList = new ArrayList<>();
    mAdapter =
        new ArrayAdapter<>(mActivity, android.R.layout.simple_list_item_1, android.R.id.text1,
            mList);
    volleyPost(mCode);
  }

  private void volleyPost(String code) {
    if (code == null) return;
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_QUERY_LIST_ADDRESS);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("pcode", code);
    params.put("memberCode", mMemberCode);
    mIsLoading = true;
    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {

          @Override public void onVolleyError(VolleyError arg0) {
            mIsLoading = false;
            mDialog.dismiss();
          }

          @Override public void onVolleyResponse(String arg0) throws JSONException {
            mIsLoading = false;
            try {
              SysDistrictListOriginal original =
                  new Gson().fromJson(arg0, SysDistrictListOriginal.class);
              if (original.getRows().size() == 0) {
                //最后一级,选择.
                setResult();
                mDialog.dismiss();
              }
              mList.clear();
              mList.addAll(original.getRows());
              mAdapter.notifyDataSetChanged();
              pbLoading.setVisibility(View.GONE);
            } catch (JsonSyntaxException e) {
              //e.printStackTrace();
              mDialog.dismiss();
            }
          }
        }

    );
  }

  @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) {
    View view = mActivity.getLayoutInflater().inflate(R.layout.dialog_address_select, null, false);
    ButterKnife.bind(this, view);
    tvAddress0.setText("");
    tvAddress0.setTag(mCode);
    lvAddress.setAdapter(mAdapter);
    lvAddress.setOnItemClickListener(this);
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle("选择地址");
    builder.setIcon(android.R.drawable.ic_dialog_info);

    builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
      @Override public void onClick(DialogInterface dialog, int which) {

        setResult();
        mDialog.dismiss();
      }
    });
    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
      @Override public void onClick(DialogInterface dialog, int which) {
        mDialog.dismiss();
      }
    });
    builder.setView(view);
    mDialog = builder.create();
    return mDialog;
  }

  private void setResult() {
    if (mItem == null) return;
    Intent i = new Intent();
    String address1 = tvAddress1.getText().toString().trim();
    String address2 = tvAddress2.getText().toString().trim();
    String address3 = tvAddress3.getText().toString().trim();
    String address4 = tvAddress4.getText().toString().trim();
    i.putExtra(EXTRA_NAME, address1 + address2 + address3 + address4);
    i.putExtra(EXTRA_CODE, mItem.getCode());
    i.putExtra(EXTRA_CODE_DISTRICT, mItem.getDistrictCode());
    getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, i);
  }

  @OnClick({
      R.id.tv_address0, R.id.tv_address1, R.id.tv_address2, R.id.tv_address3, R.id.tv_address4
  }) public void onClick(View view) {
    if (view == null) return;
    switch (view.getId()) {
      case R.id.tv_address0:
        mLevel = 0;
        tvAddress1.setText("");
        tvAddress2.setText("");
        tvAddress3.setText("");
        tvAddress4.setText("");
      case R.id.tv_address1:
        mLevel = 1;
        tvAddress2.setText("");
        tvAddress3.setText("");
        tvAddress4.setText("");
        break;
      case R.id.tv_address2:
        mLevel = 2;
        //tvAddress2.setText("");
        tvAddress3.setText("");
        tvAddress4.setText("");
        break;
      case R.id.tv_address3:
        mLevel = 3;
        //tvAddress2.setText("");
        //tvAddress3.setText("");
        tvAddress4.setText("");
        break;
      case R.id.tv_address4:
        mLevel = 4;
        break;
    }
    String code = (String) view.getTag();
    volleyPost(code);
  }

  @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    SysDistrict item = mAdapter.getItem(position);
    if (item == null) return;
    /**如果上一个接口还没执行完,这时不可点击操作*/
    if (mIsLoading) return;
    mItem = item;
    mLevel++;
    switch (mLevel) {
      case 1:
        tvAddress1.setText(item.getDistrictName());
        tvAddress1.setTag(item.getCode());
        break;
      case 2:
        tvAddress2.setText(item.getDistrictName());
        tvAddress2.setTag(item.getCode());
        break;
      case 3:
        tvAddress3.setText(item.getDistrictName());
        tvAddress3.setTag(item.getCode());
        break;
      case 4:
        tvAddress4.setText(item.getDistrictName());
        tvAddress4.setTag(item.getCode());
        break;
    }
    volleyPost(item.getCode());
  }
}
